package com.hch.web;


import com.hch.domain.Comment;
import com.hch.domain.User;
import com.hch.service.BlogService;
import com.hch.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;

@Controller
public class CommentController {

    @Autowired
    private CommentService commentService;

    @Autowired
    private BlogService blogService;

    @Value("${comment.adminavatar}")
    private String adminavatar;
    @Value("${comment.useravatar}")
    private String useravatar;

    //获取评论
    @GetMapping("/comments/{blogId}")
    public String comments(@PathVariable Long blogId, Model model) {
        model.addAttribute("comments", commentService.listCommentByBlogId(blogId));

        return "blog :: commentList";
    }

    //提交评论,拿到管理员的部分信息
    @PostMapping("/comments")
    public String postComment(Comment comment, HttpSession session) {
        Long blogId = comment.getBlog().getId();
        //通过blog的id查询到blog对象设置到comment中
        comment.setBlog(blogService.getBlog(blogId));
        User user = (User) session.getAttribute("user");
        if (user != null) {
            //当前管理员登录了
            comment.setAvatar(user.getAvatar());
            comment.setAdminComment(true);
            System.out.println(comment);
        } else {
            comment.setAvatar(useravatar);
        }
        commentService.saveComment(comment);
        return "redirect:/comments/" + blogId;
    }

}
